/*********** CLIENT TCP **************/

#include <fcntl.h>
#include <memory.h>
#include <netdb.h> 
#include <netinet/in.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <sys/socket.h> 
#include <sys/stat.h>
#include <sys/types.h> 
#include <unistd.h>

#define SERVEUR "127.0.0.1" 
#define PORTS "55555"
#define TAILLE_BUF 256

struct addrinfo hints, *servinfo, *p;
struct sockaddrtheir_adr;

char buf[TAILLE_BUF];
int sockfd, new_fd, rv, sin_size;
char s[256];

prCreationSocket() {

    int numbytes;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    rv = getaddrinfo(SERVEUR, PORTS, &hints, &servinfo);
    if (rv != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }

    // Création socket et attachement
    for (p = servinfo; p != NULL; p = p->ai_next) {
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
            perror(" client: socket");
            continue;
        }
        if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
            close(sockfd);
            perror("client: connect");
            continue;
        }
        break;
    }

    if (p == NULL) {
        fprintf(stderr, "server: failed to bind\n");
        return 2;
    }
    freeaddrinfo(servinfo); // Libère structure


}

prEnvoiMessage() {
    int numbytes;
    char message[256];

    while (message != "fini") {
        printf("Entrez un message \n");
        fgets(message, 255, stdin);

        if ((numbytes = send(sockfd, message, strlen(message), 0)) == -1) {
            printf("Erreur envoie\n");
        }

        if ((numbytes = recv(sockfd, s, 100 - 1, 0)) == -1) {
            perror("recv");
        }
        printf("Message reçu : %s\n", s);
    }
    close(sockfd);
}

prEnvoiFichier() {

    int n, f, cpt;
    bzero(buf, 256);

    f = open("./testClient.txt", O_RDONLY);

    if (f == -1) {
        perror("client: erreur ouverture fichier de lecture.\n");
        exit(3);
    }

    printf("Fichier ouvert en lecture\n");
    printf("Demarrage envoie fichier au serveur\n");

    while ((cpt = read(f, buf, TAILLE_BUF)) > 0) {
        printf("Lecture de %d octets dans fichier ouvert\n", cpt);
        n = send(sockfd, buf, cpt, 0);

        if (n < 0) {
            perror("ERROR writing to socket");
        }
        printf("%d octets envoyes au serveur: %s\n", n, buf);
    }

    if (cpt == -1) {
        perror("client: erreur lecture fichier.\n");
        exit(3);
    }

    printf("Fichier envoye avec succes.\n");
    close(f);
    freeaddrinfo(servinfo); // Libère structure

}

prLogin() {

}

main(int argc, char *argv[]) {
    printf("Creation de socket\n");
    prCreationSocket();
    printf("Envoi de messages \n");
    prEnvoiMessage();
    //printf("Envoi de fichier \n");
    //prEnvoiFichier();


    //scanf("%s",s);
    //printf("%s \n",s);

}
